package cc.yaomm.common.basic.captcha.handler;

import cc.yaomm.common.basic.enums.CaptchaType;
import cc.yaomm.common.basic.captcha.config.CaptchaProperties;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * Created by XQL on 2020/5/14.
 */
public interface CaptchaHandler {

    StringRedisTemplate getRedisTemplate();

    /**
     * <p>@Description : 生成验证码</p>
     * <p>@Author : QiLin.Xing </p>
     * <p>@Date : 2020/5/14  </p>
     *
     * @param captchaType 验证码类型
     * @param payload     发送对象（手机号、账号、邮件账号、sessionId)等
     * @param params
     * @return
     */
    String generate(CaptchaType captchaType, String payload, Object... params);

    /**
     * <p>@Description : 验证验证码</p>
     * <p>@Author : QiLin.Xing </p>
     * <p>@Date : 2020/5/20  </p>
     *
     * @param payload 发送对象（手机号、账号、邮件账号、sessionId）等
     * @param code    验证码
     * @return
     */
    default boolean verify(CaptchaType captchaType, String payload, String code) {
        //缓存验证 设置有效期
        String cacheKey = CaptchaProperties.CAPTCHA_PREFIX.concat(":").concat(captchaType.name()).concat(":").concat(payload);
        Object cacheValue = this.getRedisTemplate().opsForValue().get(cacheKey);
        boolean result = cacheValue != null && cacheValue.toString().equalsIgnoreCase(code);
        if (result) {
            this.getRedisTemplate().delete(cacheKey);
        }
        return result;
    }

    /**
     * <p>@Description : 设置验证码</p>
     * <p>@Author : QiLin.Xing </p>
     * <p>@Date : 2020/5/28  </p>
     */
    default void setCache(CaptchaType captchaType, String payload, String captcha, long expire) {
        //缓存验证 设置有效期
        String cacheKey = CaptchaProperties.CAPTCHA_PREFIX.concat(":").concat(captchaType.name()).concat(":").concat(payload);
        this.getRedisTemplate().opsForValue().set(cacheKey, captcha, expire, TimeUnit.SECONDS);
    }
}
